from django.conf import settings
from django.db.models import Q
from django.shortcuts import render
from django.views.generic.base import View
from utils.mixin_utils import LoginRequiredMixin
from pure_pagination import Paginator, PageNotAnInteger
from systems.models import OperationLog


# 操作日志视图(所有用户可见)
class ListView(LoginRequiredMixin, View):
    def get(self, request):
        v_search = request.GET.get('search')
        if v_search:
            v_search = v_search.strip()
            v_objs = OperationLog.objects.filter(Q(request_modular__icontains=v_search) | Q(request_method__icontains=v_search) |
                                                 Q(request_path__icontains=v_search) | Q(request_body__icontains=v_search)|
                                                 Q(request_ip__icontains=v_search) | Q(response_code__icontains=v_search)|
                                                 Q(json_result__icontains=v_search) | Q(creator__icontains=v_search)
                                                 ).order_by('-create_datetime')
        else:
            v_objs = OperationLog.objects.all().order_by('-create_datetime')

        # 分页功能实现
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(v_objs, per_page=settings.PAGE_NUM, request=request)
        p_objs = p.page(page)
        p_start = (int(page) - 1) * settings.PAGE_NUM  # 避免分页后每行数据序号从1开始

        return render(request, 'systems/operation_log_list.html', {'p_objs': p_objs,
                                                                   'p_start': p_start,
                                                                   'p_sum': v_objs.count(),
                                                                   'h_search': v_search})
